﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCDemo.Models;
using System.Text;

namespace MVCDemo.Controllers
{
    public class CityController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            CitiesDbContext db = new CitiesDbContext();
            return View(db.Cities);
        }

        [HttpPost]
        public string Index(IEnumerable<City> cities)
        {
            if (cities.Count(x => x.IsSelected) == 0)
            {
                return "You didn't selected any city";
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("You selected - ");
                foreach (var city in cities)
                {
                    if (city.IsSelected)
                    {
                        sb.Append(city.Name + ",");
                    }
                }
                sb.Remove(sb.ToString().LastIndexOf(","), 1);

                return sb.ToString();
            }
        }

        [HttpGet]
        public ActionResult ListBox()
        {
            CitiesDbContext db = new CitiesDbContext();
            List<SelectListItem> listSelectListItem = new List<SelectListItem>();

            foreach (City city in db.Cities)
            {
                SelectListItem item = new SelectListItem()
                {
                    Text = city.Name,
                    Value = city.ID.ToString(),
                    Selected = city.IsSelected
                };
                listSelectListItem.Add(item);
            }

            CitiesViewModel citiesViewModel = new CitiesViewModel();
            citiesViewModel.Cities = listSelectListItem;
            return View(citiesViewModel);
        }

        [HttpPost]
        public string ListBox(IEnumerable<string> selectedCities)
        {
            if (selectedCities == null)
                return "You did not selected any city";
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("You selected - " + string.Join(",",selectedCities));
                return sb.ToString();
            }
        }
    }
}
